<?php
namespace app\home\controller;

use app\common\model\Post as P;
use app\common\validate\User as UserVali;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;
use  app\common\model\User;

class Member extends Base
{

    public function index()
    {
        $where["uid"] = session("UID");
        //我的文章
        $list = P::with(["userInfo","cate"])->where($where)->order("id desc")->paginate(10);
        $myselfPost =  Db::name("post")->where($where)->count();
        $myselfReadSum =  Db::name("post")->where($where)->sum("read_count");

        //收藏文章
        $postIds = Db::name("post_collection")->where("uid",session("UID"))->column("post_id");
        $collectionCount = Db::name("post_collection")->where("uid",session("UID"))->count();
        $postCollection = P::with(["userInfo","cate"])->whereIn("id",$postIds)->order("id desc")->paginate(10);


        //用户信息
        $userInfo = Db::name("user")->field("username,avatar,integral,email,intro")->where($where)->find();
        View::assign("list",$list);
        View::assign("postCollection",$postCollection);
        View::assign("collectionCount",$collectionCount);
        View::assign("myselfPost",$myselfPost);
        View::assign("myselfReadSum",$myselfReadSum);
        View::assign("userInfo",$userInfo);
        return View::fetch("/user/index");
    }

    public function wxlogin()
    {
        return View::fetch("/user/wx-login");
    }

    public function login()
    {
        if (request()->isAjax()){
            $user = input("user");
            $password = md5(input("password"));

            if (isEmail($user)){
                $data["email"] =$user;
            }else{
                $data["username"] = $user;
            }

            $data["password"] = $password;
            $data["user_type"] = 0;
            $userId = Db::name("user")->where($data)->value("uid");
            $userStatus = Db::name("user")->where($data)->value("status");
            if ($userStatus == 1){
                return json(["code" => 0 ,"msg" => "该用户已被禁用，无法登陆"]);
            }
            if ($userId){
                session("UID",$userId);
                return json(["code" => 1 ,"msg" => "登录成功"]);
            }
            return json(["code" => 0 ,"msg" => "用户名或密码错误"]);

        }else{
            return View::fetch("/user/login");
        }
    }

    public function register()
    {
        if (request()->isAjax()){
            $data = input("post.");
            try {
                validate(UserVali::class)->check($data);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                return json(["code" => 0,"msg" =>$e->getError()]);
            }

            if ($data["emailCode"] != cache($data["email"])){
                return json(["code" => 0,"msg" =>"邮箱验证码不正确"]);
            }

            $data["password"] = md5($data["password"]);
            $data["group_id"] = 2;
            $create = User::create($data);
            if ($create){
                return json(["code" => 1,"msg" =>"注册成功"]);
            }
            return json(["code" => 0,"msg" =>"注册失败"]);
        }else{
            return View::fetch("/user/register");
        }
    }

    public function sendEmailCode()
    {
        $email = input("email");
        if (!isEmail($email)){
            return json(["code" => 0,"msg" =>"邮箱格式错误"]);
        }
        $randEmailCode = rand(10000,99999);
        $content = "注册码为：" .$randEmailCode ."，30分钟内有效";
        $rel = sendEmail($email,"【天年网络】注册会员",$content);
        if ($rel){
            cache($email,$randEmailCode,1800);
            return json(["code" => 1,"msg" =>"验证码已发送至邮箱"]);
        }
        return json(["code" => 0,"msg" =>"验证码发送失败"]);
    }
    public function logout()
    {
        session("UID",NULL);

        return "<script>location.href='/'</script>";
    }

    public function upload()
    {
        $file = request()->file("Image");

        try {
            $savePath = \think\facade\Filesystem::disk('public')->putFile( 'uploads/avatar', $file);
            $saveAvatar = Db::name("user")->where("uid",session("UID"))->update(["avatar" => DIRECTORY_SEPARATOR .$savePath]);
            if ($saveAvatar){
                return json(["code" =>1,"msg" =>"上传成功"]);
            }
            return json(["code" =>0,"msg" =>"上传失败"]);
        } catch (think\exception\ValidateException $e) {
            return json(["code" =>0,"msg" =>$e->getMessage()]);
        }
    }
    public function updateUser()
    {
        $data = input("post.");
        $update = Db::name("user")->where("uid",session("UID"))->update($data);
        if($update){
            return json(["code" => 1, "msg" => "修改成功"]);
        }
        return json(["code" => 0, "msg" => "修改失败"]);
    }

    public function rePassword()
    {
        $oldPassword = input("oldPassword");
        $password = input("password");
        $where["uid"] = session("UID");
        $where["password"] = md5($oldPassword);
        $res = Db::name("user")->where($where)->find();
        if ($res){
            $rePassword = User::update(["password" => md5($password)],["uid"=> session("UID")]);
            if ($rePassword){
                return json(["code" => 1, "msg" => "修改成功"]);
            }
            return json(["code" => 0, "msg" => "修改失败"]);
        }
        return json(["code" => 0, "msg" => "原密码错误"]);
    }
}